package cn.murky.quartz.config;

import lombok.extern.slf4j.Slf4j;
import org.quartz.spi.ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class MurkyQuartzVirtualThreadPool implements ThreadPool {
    /**
     * 虚拟线程池
     */
    private ExecutorService executorService;
    private List<Future<?>> tasks;
    private boolean isShutdown = false;
    /**
     * 虚拟线程不限制线程数
     */
    private static final Integer MAX_THREAD = Integer.MAX_VALUE;

    public MurkyQuartzVirtualThreadPool() {
        tasks = new ArrayList<>();
    }

    @Override
    public boolean runInThread(Runnable runnable) {
        if (runnable == null) {
            return false;
        }
        if (isShutdown) {
            debug("ThreadPool is shutdown");
        }
        if (executorService.isShutdown()) {
            throw new RejectedExecutionException("ThreadPool is shutdown");
        }
        executorService.submit(runnable);
        return true;
    }

    @Override
    public int blockForAvailableThreads() {
        if (isShutdown) {
            return 0;
        }
        if (executorService.isShutdown()) {
            return 0;
        }
        return MAX_THREAD;
    }

    @Override
    public void initialize() {
        this.executorService = Executors.newThreadPerTaskExecutor(r -> new Thread(r, "MurkyQuartzVirtualThreadPool"));
    }

    @Override
    public void shutdown(boolean waitForJobsToComplete) {
        debug("Shutting down threadpool...");
        isShutdown = true;
        // 没有线程任务则直接停止
        if (waitForJobsToComplete) {
            try {
                this.executorService.awaitTermination(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        this.executorService.shutdown();
    }

    @Override
    public int getPoolSize() {
        return MAX_THREAD;
    }

    @Override
    public void setInstanceId(String schedInstId) {

    }

    @Override
    public void setInstanceName(String schedName) {

    }

    private void debug(String content) {
        log.debug(STR."[MurkyQuartzVirtualThreadPool] -> \{content}");
    }

    public void setThreadCount(int threadCount){

    }

    public void setThreadPriority(int threadPriority) {

    }

    public void setThreadsInheritContextClassLoaderOfInitializingThread(boolean b) {

    }
}
